package net.osweb.core.tools.utils.excel;

import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.osweb.core.tools.exception.ExcelParseException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ExcelExportUtil {

	private static Log log = LogFactory.getLog(ExcelExportUtil.class);
	/**
	 * objOut存放�?要导出的数据    objIn存放Response对象(用于获得返回前台页面的输出流),Excel的列名以及文件名
	 * 
	 * */
	@SuppressWarnings("unchecked")
	public static void exportExcel(Map<String, Object> objIn,
			Map<String, Object> objOut) throws ExcelParseException{
		try {
			// 取得response HttpServletResponse
			HttpServletResponse response = (HttpServletResponse) objIn
					.get("response");

			String fileName = (String)objIn.get("fileName");
			Long numTag = new Date().getTime()-1303290794406l;
			while(numTag>334750){
				numTag -=12345l; 
			}
			
			
			// 设置table列名
			List<String> excelColName = (List<String>) objIn.get("excelColName");
			OutputStream os = response.getOutputStream();// 取得输出�?
			response.reset();// 清空输出�?
			response
					.setHeader("Content-disposition", "attachment; filename="
							+ new String((fileName + numTag).getBytes("GB2312"), "8859_1")
							+ ".xls");// 设定输出文件�?
			response.setContentType("application/msexcel");// 定义输出类型

			WritableWorkbook wwb = Workbook.createWorkbook(os); // 建立excel文件

			WritableSheet ws = wwb.createSheet("Sheet1", 10); // 创建�?个工作表

			// 设置单元格的文字格式
			WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLUE);
			WritableCellFormat wcf = new WritableCellFormat(wf);
			wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
			wcf.setAlignment(Alignment.CENTRE);
			ws.setRowView(0, 500);

			// 填充数据的内�?
			List<List<String>> resultList = (List<List<String>>) objOut.get("resultList");
			// 设置列头�?
			for (int i = 0; i < excelColName.size(); i++) {
				ws.addCell(new Label(i, 0, excelColName.get(i), wcf));
			}
			// 设置内容
			wcf = new WritableCellFormat();
			for (int i = 0; i < resultList.size(); i++) {
				for (int j = 0; j < excelColName.size(); j++) {
					ws.addCell(new Label(j, i + 1, resultList.get(i).get(j),
							wcf));
				}
			}
			wwb.write();
			wwb.close();

		} catch (Exception e) {
			log.error(e);
			throw new ExcelParseException(e);
		}
	}

}
